import React, { useState, useReducer, useMemo, useEffect, useRef } from 'react';
import { createModel } from 'hox';
import { message } from 'antd';
import { findIndex } from 'lodash';
import {
  getCustomMessage,
  getFn,
  deleteFlow,
  updateFlow,
  addFlow,
  queryFtpFileType,
  getFlowSingle,
  getFlowAll,
} from './service.js';
import { useRequest } from '@umijs/hooks';

class Fields {
  customAllList = [];
  fnList = [];
  isAddMode = true;
  checkedList = [];
  indeterminate = false;
  checkAll = false;
  selectedIndex = null;
  flowListVisible = false;
  selectedRow = {};
  flowName = '';
  ftpFileType = [];
  flowRowData = {};
}
const reducer = (state, action) => {
  switch (action.type) {
    case 'updateState':
      return { ...state, ...action.payload };
    default:
      throw new Error();
  }
};
function useModel() {
  const initState = useMemo(() => new Fields(), []);

  const [state, dispatch] = useReducer(reducer, {
    ...initState,
  });

  const clearAll = () => {
    dispatch({
      type: 'updateState',
      payload: { ...new Fields() },
    });
  };

  const setState = payload => {
    dispatch({
      type: 'updateState',
      payload,
    });
  };
  //获取当前流程
  const currentFlowProps = useRequest(getFlowSingle, {
    manual: true,
    onSuccess: (res, params) => {},
  });
  //获取全部流程
  const { loading, run, data } = useRequest(getFlowAll, {
    manual: true,
    onSuccess: async (result, params) => {},
  });
  //初始加载
  const initLoad = async () => {
    let localStorageState =
      (localStorage.getItem('deviceType') && JSON.parse(localStorage.getItem('deviceType'))) || {};
    let result = await run({ fsuTypeId: localStorageState.id });
    if (result && state.selectedIndex === null) {
      const data = result?.data;
      if (data && data[0]) {
        let res = await currentFlowProps.run({ id: data[0].id });
        setState({
          isAddMode: false,
          selectedIndex: 0,
          flowRowData: res.data || {},
          selectedRow: data[0],
          flowName: data[0].name,
          msgType: data[0].msgType,
        });
        //设置checked列表
      } else {
        setState({
          isAddMode: true,
          selectedIndex: null,
          selectedRow: {},
          msgType: 0,
          flowName: '',
          flowRowData: {},
        });
      }
    }
  };
  //获取全部自定义列表
  const { run: getFtpFileType } = useRequest(queryFtpFileType, {
    manual: true,
    onSuccess: (res, params) => {
      if (res.result) {
        setState({ ftpFileType: res.data || [] });
      }
    },
  });
  //获取全部自定义列表
  const customProps = useRequest(getCustomMessage, {
    manual: true,
    cacheKey: 'allCustomMessage',
    onSuccess: (res, params) => {
      if (res.result) {
        setState({ customAllList: res.data || [] });
      }
    },
  });
  //获取开始节点的后端方法
  const fnProps = useRequest(getFn, {
    manual: true,
    onSuccess: (res, params) => {
      if (res.result) {
        setState({ fnList: res.data || [] });
      }
    },
  });
  //编辑流程
  const edit = async item => {
    if (item.id === state.flowRowData.id) {
      return;
    }
    let res = await currentFlowProps.run({ id: item.id });
    if (res && res.result) {
      setState({
        flowRowData: res.data && { ...res.data },
        isAddMode: false,
        flowName: item.name,
      });
    }
  };
  //删除流程
  const remove = async params => {
    let keys = params.keys;
    let res = await deleteFlow(params);
    if (res.result) {
      let localStorageState =
        (localStorage.getItem('deviceType') && JSON.parse(localStorage.getItem('deviceType'))) ||
        {};
      run({ fsuTypeId: localStorageState.id });
      setState({
        checkedList: [],
        selectedRow: {},
        checkAll: false,
        indeterminate: false,
        flowName: keys.includes(state.flowRowData.id) ? '' : state.flowName,
        isAddMode: keys.includes(state.flowRowData.id) ? true : false,
        flowRowData: keys.includes(state.flowRowData.id) ? {} : state.flowRowData,
      });
    }
  };
  //保存更新流程
  const save = async (flowRowData, fields, flowData) => {
    if (!fields.flowName) {
      message.error('请填写流程名称！');
      return;
    }
    let params = {
      name: fields.flowName,
      fsuTypeId: JSON.parse(localStorage.getItem('deviceType')).id,
      content: JSON.stringify(flowData),
    };
    let res;
    if (state.isAddMode) {
      res = await addFlow(params);
    } else {
      res = await updateFlow({ ...params, id: flowRowData.id });
    }

    if (res.result) {
      let localStorageState =
        (localStorage.getItem('deviceType') && JSON.parse(localStorage.getItem('deviceType'))) ||
        {};
      let result = await run({ fsuTypeId: localStorageState.id });

      const updateState = {
        flowName: fields.flowName,
        flowRowData: { ...flowRowData, content: JSON.stringify(flowData) },
      };

      if (state.isAddMode && result?.data && result?.data[0]) {
        const flowList = result?.data || [];
        const len = flowList?.length - 1 || 0;
        const item = flowList[len];
        updateState['flowRowData'] = {
          id: item?.id,
          name: item.name,
          content: JSON.stringify(flowData),
        };
      }

      setState({
        ...updateState,
      });
      message.success('请求成功!');
    } else {
      message.error(res.msg);
    }
  };
  //新增流程
  const add = () => {
    setState({
      isAddMode: true,
      selectedIndex: null,
      selectedRow: {},
      flowName: '',
      flowListVisible: false,
      flowRowData: {},
    });
  };
  //返回值
  return {
    state: {
      ...state,
      data: data?.data || [],
    },
    run,
    customProps,
    fnProps,
    currentFlowProps,
    clearAll,
    setState,
    remove,
    initLoad,
    getFtpFileType,
    add,
    edit,
    save,
  };
}
export default createModel(useModel);
